<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue'
import { useBaseApi } from '@/api/base'
import { themeConfig } from '@/storage'
import type { CalendarRowType, WaitRowType } from '@/views/home/interface'
// import { useMisApi } from '@/api/mis'
// import HomeWait from '@/views/home/components/HomeWait.vue'
// import { dayjs } from 'element-plus'

// const { GetOwnTodo } = useMisApi()
const { GetYearWorkCalendar } = useBaseApi()

// 剩余天数置顶范围（reminderDays来源主题系统设置）
const { reminderDays } = themeConfig.value
const diffDays: number[] = []
for (let i = -reminderDays; i <= reminderDays; i++) diffDays.push(i)

const loading = ref(false)
const current = ref(new Date())
const currentWaitDate = ref('')
const currentYear = ref(new Date().getFullYear())
const items = ref<CalendarRowType[]>([])
const waitItems = ref<WaitRowType[]>([])

const onFetch = () => {
  loading.value = true
  const year = current.value.getFullYear()
  GetYearWorkCalendar({ year })
    .then(({ data }) => {
      items.value = data
      currentYear.value = year
    })
    .finally(() => (loading.value = false))
}

// const onFetchWait = async () => {
//   const { data } = await GetOwnTodo<WaitRowType[]>()

//   const list = data.map((v) => {
//     const date = new Date()
//     const end_date = new Date(v.end_date)
//     // 获取两个日期的时间戳差值
//     const diffTime = end_date.getTime() - date.getTime()
//     // 计算相差的天数
//     v.diffDays = Math.ceil(diffTime / (1000 * 3600 * 24))
//     // 去掉时分秒
//     v.end_date_day = dayjs(v.end_date).format('YYYY-MM-DD')
//     return v
//   })

//   // 范围内置顶
//   list.sort((a, b) => {
//     const includeA = diffDays.includes(a.diffDays)
//     const includeB = diffDays.includes(b.diffDays)
//     if (includeA && !includeB) return -1
//     if (includeB && !includeA) return 1
//     return a.diffDays - b.diffDays
//   })

//   waitItems.value = list
// }

const toMonth = (data: DateCellType) => {
  return data.date.getMonth() === current.value.getMonth()
}

const isDay = (data: any): CalendarRowType | undefined => {
  return items.value.find((s) => s.year_month_day === data.day)
}

const getWait = (data: DateCellType) => {
  return waitItems.value.filter((f) => f.end_date_day === data.day)
}

const getDiffDaysClass = (data: DateCellType) => {
  const list = getWait(data)
  const diffDays = list.map((v) => v.diffDays)
  const diff = Math.min(...diffDays)
  let className
  const classNameColor = {
    success: 'color-success border-success',
    danger: 'color-danger border-danger',
    warning: 'color-warning border-warning'
  }
  if (!data.isSelected) {
    classNameColor.success = 'bg-success color-white'
    classNameColor.danger = 'bg-danger color-white'
    classNameColor.warning = 'bg-warning color-white'
  }
  if (diff < 0) {
    className = classNameColor.success
  } else if (diff <= 1) {
    className = classNameColor.danger
  } else if (diff <= reminderDays) {
    className = classNameColor.warning
  } else className = ''
  return className
}

const onDateCellClick = (data: DateCellType) => {
  const list = waitItems.value.filter((f) => f.end_date_day === data.day)
  if (data.day === currentWaitDate.value || !list.length) {
    currentWaitDate.value = ''
  } else {
    currentWaitDate.value = data.day
  }
}

watch(
  () => current.value,
  () => {
    const year = current.value.getFullYear()
    if (currentYear.value !== year) onFetch()
  }
)

onMounted(() => {
  onFetch()
})
</script>
<template>
  <div class="custom-calendar">
    <el-calendar v-model="current" v-loading="loading">
      <template #date-cell="{ data }">
        <div
          v-if="toMonth(data)"
          class="custom-date flex flex-column align-center justify-center"
          @click="onDateCellClick(data)"
        >
          <span>{{ data.day.split('-').slice(2).join('-') }}</span>
          <div v-if="isDay(data)" class="font12">
            <span v-if="isDay(data)?.is_work" class="color-primary work">班</span>
            <span v-else class="color-danger work">休</span>
            <span class="font10 dot" :class="isDay(data)?.is_work ? 'bg-primary' : 'bg-danger'" />
          </div>
          <span v-else-if="[0, 6].includes(data.date.getDay())" class="color-danger work font10"
            >休</span
          >
          <div
            v-if="getWait(data).length"
            class="font12 text-center w100"
            style="border-radius: 8px"
            :class="getDiffDaysClass(data)"
          >
            <span>待办 {{ getWait(data).length }}</span>
          </div>
        </div>
        <div v-else class="custom-date flex flex-column align-center justify-center">
          <span>{{ data.day.split('-')[2] }}</span>
          <div
            v-if="getWait(data).length"
            class="font12 text-center w100"
            style="border-radius: 8px"
            :class="getDiffDaysClass(data)"
          >
            <span>待办 {{ getWait(data).length }}</span>
          </div>
        </div>
      </template>
    </el-calendar>
    <!-- <HomeWait v-model="currentWaitDate" @fetch="onFetchWait" :items="waitItems" class="duration2 animate__animated animate__fadeInUp" /> -->
  </div>
</template>

<style lang="scss" scoped>
.custom-calendar {
  user-select: none;
}

.custom-date {
  position: relative;
  height: 30px;

  .work {
    position: absolute;
    top: 0;
    right: 3px;
  }

  .dot {
    position: absolute;
    top: 3px;
    left: 3px;
    width: 5px;
    height: 5px;
    border-radius: 50%;
  }
}
</style>
